
//导入依赖包
const http = require("http");
const path = require("path");
const url = require("url");
const express= require('express');


const superagent = require("superagent");
const cheerio = require("cheerio");


let router = express.Router();
module.exports = router;

router.get('/',(req,res)=>{
    superagent.get("http://www.viviun.com/Rentals/")
    .end((error, response) => {
        if(response){
            //获取页面文档数据
            var content = response.text;
            //cheerio也就是nodejs下的jQuery  将整个文档包装成一个集合，定义一个变量$接收
            let $ = cheerio.load(content);
            //定义一个空数组，用来接收数据
            let result=[];
            //分析文档结构  先获取每个li 再遍历里面的内容(此时每个li里面就存放着我们想要获取的数据)
            $("table tbody tr td .top tbody tr td table tbody tr td table tbody tr td table tbody tr").each((index,value)=>{
                if(index%2==0){
                    let money = $(value).find("td").eq(1).find("font").text().split(' ')[0].replace(/\$/g,'');
                    result.push({
                        title:$(value).find("td font h3 a").text(),
                        link:$(value).find("td font h3 a").attr('href'),
                        money:money,
                        img_src:'',
                        content:''
                    })
                }else{
                    // i => 修改result第i个的属性
                    let i = (index-1)/2;
                    result[i]['img_src']=$(value).find("td a img").attr('src');
                    result[i]['content']=$(value).find("td font").text().replace(/\n/g,'').replace(/\$/g,'');
                }
            })
            res.send(result)
        }
    })
})
